package com.bmft.util.file;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author Jarvan
 * @version 1.0
 * @create 2020/12/3 20:54
 */
@Slf4j
@Component
public class FileUtil {
    private static String baseFilePath = "D:/file";
    /**
     *
     * @param file
     * @param userFilePath 用户文件夹 就是用户名
     */
    public boolean createLocalFile(String userFilePath, MultipartFile file) {
        //file path
        String filePath =baseFilePath+"/"+userFilePath;
        //通过filepath构建localFile
        File localFile = new File(filePath);
        //如果localFile吗目录不存在先创建目录
        if (!localFile.exists()){
            localFile.mkdirs();
        }
        //filepath + filename
        String originalFilename = file.getOriginalFilename();
        String path = filePath+"/"+originalFilename;

        log.info("createLocalFile path = {}", path);
        //path 就是文件真正的路径 这里我们然后将文件写入
        localFile = new File(path);
        FileOutputStream fos = null;
        InputStream in = null;
        try {

            if(localFile.exists()){
                //如果文件存在删除文件
                boolean delete = localFile.delete();
                if (delete == false){
                    log.error("Delete exist file \"{}\" failed!!!",path,new Exception("Delete exist file \""+path+"\" failed!!!"));
                }
            }
            //如果文件不存在，则创建新的文件
            if(!localFile.exists()){
                localFile.createNewFile();
                log.info("Create file successfully,the file is {}",path);
            }

            //最后通过inputString写入文件。
            fos = new FileOutputStream(localFile);
            in = file.getInputStream();
            //缓冲.
            byte[] bytes = new byte[1024];

            int len = -1;

            while((len = in.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }

            fos.flush();
            log.info("Reading uploaded file and buffering to local successfully!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            try {
                if(fos != null) {
                    fos.close();
                }
                if(in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("InputStream or OutputStream close error : {}", e);
                return false;
            }
        }

        return true;
    }
}
